<template>
  <div id="banner" class="banner">
    <!--动态将图片轮播图的容器高度设置成与图片一致-->
    <el-carousel
      :height="bannerHeight + 'px'"
      :style="maxHeight"
      arrow="never"
      ref="slideCarousel"
    >
      <!--遍历图片地址,动态生成轮播图-->
      <el-carousel-item v-for="item in img_list" :key="item.url">
        <img :src="item.url" alt />
      </el-carousel-item>
    </el-carousel>
  </div>
</template>
<script>
export default {
  name: "Banner",

  data() {
    return {
      // 图片地址数组
      img_list: [
        { url: require("@/assets/banner/banner1.jpg") },
        { url: require("@/assets/banner/banner2.jpg") },
        { url: require("@/assets/banner/banner3.jpg") },
        { url: require("@/assets/banner/banner4.jpg") },
      ],
      bannerHeight: 200, // 图片父容器高度
      screenWidth: 0, // 浏览器宽度
      maxHeight: { maxHeight: "315px" },
    };
  },

  methods: {
    setSize: function () {
      // 通过浏览器宽度(图片宽度)计算高度
      this.bannerHeight = (300 / 700) * this.screenWidth;
    },
    slideBanner() {
      //选中的轮播图
      var box = document.querySelector(".el-carousel__container");
      var startPoint = 0;
      var stopPoint = 0;
      //重置坐标
      var resetPoint = function () {
        startPoint = 0;
        stopPoint = 0;
      };
      //手指按下
      box.addEventListener("touchstart", function (e) {
        //手指点击位置的X坐标
        startPoint = e.changedTouches[0].pageX;
      });
      //手指滑动
      box.addEventListener("touchmove", function (e) {
        //手指滑动后终点位置X的坐标
        stopPoint = e.changedTouches[0].pageX;
      });
      //当手指抬起的时候，判断图片滚动离左右的距离
      let that = this;
      box.addEventListener("touchend", function (e) {
        if (stopPoint == 0 || startPoint - stopPoint == 0) {
          resetPoint();
          return;
        }
        if (startPoint - stopPoint > 0) {
          resetPoint();
          that.$refs.slideCarousel.next();
          return;
        }
        if (startPoint - stopPoint < 0) {
          resetPoint();
          that.$refs.slideCarousel.prev();
          return;
        }
      });
    },
  },
  mounted() {
    if (this.$refs.slideCarousel) this.slideBanner();
    // 首次加载时,需要调用一次
    this.screenWidth = window.innerWidth;
    this.setSize(); // 窗口大小发生改变时,调用一次
    window.onresize = () => {
      this.screenWidth = window.innerWidth;
      this.setSize();
    };
  },
};
</script>
<style>
/* 轮播图图片 */
.banner img {
  /*   设置图片宽度和浏览器宽度一致 */
  width: 100%;
  height: 100%;
}
/* 轮播图容器大小 */
.banner .el-carousel .el-carousel__container {
  max-height: 315px;
}
</style>
